package com.zygh.lz.controller.app;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.controller.FileUpload;
import com.zygh.lz.entity.Section;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.app.AppPark;
import com.zygh.lz.entity.app.AppParkArea;
import com.zygh.lz.service.AppParkAreaService;
import com.zygh.lz.service.SectionService;
import com.zygh.lz.service.StaffService;
import com.zygh.lz.service.impl.AppParkService;
import com.zygh.lz.stapprove.*;
import com.zygh.lz.util.GetRandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "App拖车停车场管理模块", description = "AppParkController")
@RestController
public class AppParkController {
    @Resource
    private AppParkService appParkService;
    @Resource
    private StaffService staffService;

    @Resource
    private AppParkAreaService appParkAreaService;
    @Resource
    private SectionService sectionService;

    @Value("${trailer.picture-path}")
    private String picturePath;


    @ApiOperation("App拖车停车场信息查询")
    @RequestMapping(value = "/findAppParkAllBySearch", method = RequestMethod.POST)
    @ViLog(logType = "2", module = "App拖车停车场管理模块>停车场信息查询")
    public OutBean findAppParkAllBySearch(@RequestBody(required = false) InBean inBean) {

        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        String policeNumber = jsonObject.getString("policeNumber");
        String searchContent = jsonObject.getString("searchContent");
        int current = Integer.valueOf(jsonObject.getString("current"));
        int size = Integer.valueOf(jsonObject.getString("size"));
        if (StringUtils.isEmpty(policeNumber)) {
            return OutBeanUtil.resErr("查询失败无警员信息", inBean);
        }
        Staff staff = staffService.getOne(Wrappers.<Staff>lambdaQuery().eq(Staff::getStaffNum, policeNumber));
        Section one = sectionService.getOne(Wrappers.<Section>lambdaQuery().eq(Section::getSysSectionId, staff.getSysSectionId()).last("limit 1"));
        PageHelper.startPage(current, size);
        List<AppPark> appParkList = appParkService.list(Wrappers.<AppPark>lambdaQuery().eq(AppPark::getDeptId, one.getSectionPid()).eq(AppPark::getIsDel, 0)
                .and(!StringUtils.isEmpty(searchContent), e -> e.like(!StringUtils.isEmpty(searchContent), AppPark::getName, searchContent)
                        .or().like(!StringUtils.isEmpty(searchContent), AppPark::getAddress, searchContent)));
        for (AppPark appPark : appParkList) {
            appPark.setSignPhoto(null);
//            try {
//                appPark.setSignPhoto(FileUpload.ReadPictureByPath(appPark.getSignPhoto()));
//            } catch (IllegalArgumentException e) {
//                e.printStackTrace();
//                appPark.setSignPhoto(null);
//            }
        }
        PageInfo<AppPark> pageInfo = new PageInfo<>(appParkList);
        return OutBeanUtil.resSuc(ResultUtil.resultBeansSuccess(pageInfo), inBean);
    }

    @ApiOperation("App拖车停车场详细信息查询")
    @RequestMapping(value = "/findAppParkInfoByCode", method = RequestMethod.POST)
    @ViLog(logType = "2", module = "App拖车停车场管理模块>根据编号查询停车场详情")
    public OutBean findAppParkInfoByCode(@RequestBody(required = false) InBean inBean) {

        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        String code = jsonObject.getString("code");
        AppPark appPark = appParkService.findAppParkInfoByCode(code);
        try {
            appPark.setSignPhoto(FileUpload.ReadPictureByPath(picturePath + appPark.getSignPhoto()));
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(e.getMessage());
            appPark.setSignPhoto(null);
        }
        Section one = sectionService.getOne(Wrappers.<Section>lambdaQuery().eq(Section::getSysSectionId, appPark.getDeptId()).last("limit 1"));
        appPark.setDeptName(one.getSectionName());
        return OutBeanUtil.resSuc(ResultUtil.resultBeansSuccess(appPark), inBean);
    }


    @ApiOperation("App拖车停车场信息修改")
    @RequestMapping(value = "/updateAppPark", method = RequestMethod.POST)
    @ViLog(logType = "2", module = "App拖车停车场管理模块>停车场信息修改")
    public OutBean updateAppPark(@RequestBody(required = false) InBean inBean) {
        AppPark appPark = new AppPark();
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        appPark.setId(jsonObject.getInteger("id"));
        appPark.setCode(jsonObject.getInteger("code"));
        appPark.setName(jsonObject.getString("name"));
        appPark.setAddress(jsonObject.getString("address"));
        appPark.setContactWay(jsonObject.getString("contactWay"));
        appPark.setUserNum(jsonObject.getString("policeNumber"));
        Staff staff = staffService.getOne(Wrappers.<Staff>lambdaQuery().eq(Staff::getStaffNum, appPark.getUserNum()));
        if (staff == null) {
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(502, "修改失败,未找到警员信息", null), inBean);
        }
        Section one = sectionService.getOne(Wrappers.<Section>lambdaQuery().eq(Section::getSysSectionId, staff.getSysSectionId()).last("limit 1"));
        if (one == null) {
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(502, "修改失败,未找到部门信息", null), inBean);
        }
        appPark.setApplicantName(staff.getStaffName());
        appPark.setDeptId(one.getSectionPid());
        appPark.setApplicantName(staff.getStaffName());
        appPark.setGmtUpdate(DateUtil.now());
        appPark.setSignboard(0);
        appPark.setState(0);
        String imagePath = null;
        try {
            imagePath = FileUpload.uploadImage(jsonObject.getString("signPhoto"), picturePath);
            appPark.setSignPhoto(imagePath);
            appParkService.updateById(appPark);
            String area = jsonObject.getString("parkAreaList");
            List<AppParkArea> appParkAreaList = JSON.parseArray(area, AppParkArea.class);
            for (AppParkArea appParkArea : appParkAreaList) {
                appParkArea.setParkCode(appPark.getCode());
            }
            appParkAreaService.remove(Wrappers.<AppParkArea>lambdaQuery().eq(AppParkArea::getParkCode, appPark.getCode()));
            appParkAreaService.saveBatch(appParkAreaList);
            return OutBeanUtil.resSuc(ResultUtil.resultBeansSuccess("success"), inBean);
        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(500, "修改失败,图片上传错误", null), inBean);
        }

    }


    @ApiOperation("App拖车停车场信息添加")
    @RequestMapping(value = "/addAppPark", method = RequestMethod.POST)
    @ViLog(logType = "2", module = "App拖车停车场管理模块>停车场信息添加")
    @Transactional
    public OutBean addAppPark(@RequestBody(required = false) InBean inBean) {
        AppPark appPark = new AppPark();
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        List<Integer> codeList = appParkService.getCodeList();
        int[] nums = new int[codeList.size()];
        for (int i = 0; i < codeList.size(); i++) {
            nums[i] = codeList.get(i);
        }
        int randomExcept = GetRandomUtil.getRandomExcept(1000, nums);
        appPark.setCode(randomExcept);
        appPark.setName(jsonObject.getString("name"));
        appPark.setAddress(jsonObject.getString("address"));
        appPark.setContactWay(jsonObject.getString("contactWay"));
        appPark.setUserNum(jsonObject.getString("policeNumber"));
        if (StringUtils.isEmpty(appPark.getUserNum())) {
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(500, "添加失败,未获取到警号", null), inBean);
        }
        Staff staff = staffService.getOne(Wrappers.<Staff>lambdaQuery().eq(Staff::getStaffNum, appPark.getUserNum()));
        if (staff == null) {
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(502, "修改失败,未找到警员信息", null), inBean);
        }
        Section one = sectionService.getOne(Wrappers.<Section>lambdaQuery().eq(Section::getSysSectionId, staff.getSysSectionId()).last("limit 1"));
        if (one == null) {
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(502, "修改失败,未找到部门信息", null), inBean);
        }
        appPark.setApplicantName(staff.getStaffName());
        appPark.setDeptId(one.getSectionPid());
        appPark.setGmtCreate(DateUtil.now());
        appPark.setGmtUpdate(DateUtil.now());
        appPark.setUserState(1);
        appPark.setSignboard(0);
        String imagePath = null;
        try {
            imagePath = FileUpload.uploadImage(jsonObject.getString("signPhoto"), picturePath);
            appPark.setSignPhoto(imagePath);
            appPark.setState(0);
            appParkService.save(appPark);
            String area = jsonObject.getString("parkAreaList");
            List<AppParkArea> appParkAreaList = JSON.parseArray(area, AppParkArea.class);
            for (AppParkArea appParkArea : appParkAreaList) {
                appParkArea.setParkCode(appPark.getCode());
            }
            appParkAreaService.remove(Wrappers.<AppParkArea>lambdaQuery().eq(AppParkArea::getParkCode, appPark.getCode()));
            appParkAreaService.saveBatch(appParkAreaList);
            appPark.setParkAreaList(appParkAreaList);
            return OutBeanUtil.resSuc(ResultUtil.resultBeansSuccess(appPark), inBean);
        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
            return OutBeanUtil.resSuc(ResultUtil.resultBeansCodeError(500, "添加失败,图片上传错误", null), inBean);
        }
    }

    @ApiOperation("App拖车停车场删除")
    @RequestMapping(value = "/appParkDel", method = RequestMethod.POST)
    @ViLog(logType = "2", module = "App拖车停车场管理模块>根据编号查询停车场详情")
    public OutBean appParkDel(@RequestBody(required = false) InBean inBean) {
        JSONObject jsonObject = inBean.convertObj(JSONObject.class);
        String code = jsonObject.getString("code");
        AppPark one = appParkService.getOne(Wrappers.<AppPark>lambdaQuery().eq(AppPark::getCode, code));
        String policeNumber = jsonObject.getString("policeNumber");
        if (!one.getUserNum().equals(policeNumber)) {
            return OutBeanUtil.resSuc(ResultUtil.resultBeansError("不能删除他人的备案记录", null), inBean);
        }
        appParkService.update(Wrappers.<AppPark>lambdaUpdate().eq(AppPark::getCode, code).set(AppPark::getIsDel, 1).set(AppPark::getSignboard, 0));
        return OutBeanUtil.resSuc(ResultUtil.resultBeansSuccess(null), inBean);
    }


    @ApiOperation("视频网获取停车场信息")
    @GetMapping("/internetFindAppParkAll")
    public List<AppPark> internetFindAppParkAll() {
        List<AppPark> appParkList = appParkService.internetFindAppParkAll();
        List<Integer> codeList = appParkList.stream().map(AppPark::getCode).collect(Collectors.toList());
        for (AppPark appPark : appParkList) {
            if (StringUtils.isEmpty(appPark.getSignPhoto())) {
                continue;
            }
            try {
                appPark.setSignPhoto(FileUpload.ReadPictureByPath(picturePath + appPark.getSignPhoto()));
            } catch (IllegalArgumentException e) {
//                e.printStackTrace();
                log.error(e.getMessage());
                appPark.setSignPhoto(null);
            }
        }
        if (codeList.size() > 0) {
            UpdateWrapper wrapper = new UpdateWrapper();
            wrapper.in("code", codeList);
            wrapper.setSql("signboard = signboard + 1");
            appParkService.update(wrapper);
        }
        return appParkList;
    }


    @ApiOperation("修改停车场记录同步标识(互联网使用)")
    @GetMapping("/updateAppParkByBoard")
    public Boolean updateTrailerByBoard(String code) {
        AppPark byId = appParkService.getOne(Wrappers.<AppPark>lambdaQuery().eq(AppPark::getCode, code));
        if (byId != null) {
            byId.setSignboard(1);
            return appParkService.updateById(byId);
        }
        return false;
    }

    @ApiOperation("视频网添加停车场信息")
    @PostMapping("/internetUpdateAppPark")
    public Boolean internetFindAppParkAll(@RequestBody AppPark appPark) {
        appPark.setId(null);
        appPark.setState(0);
        appPark.setGmtUpdate(DateUtil.now());
        appPark.setGmtUpdate(DateUtil.now());
        List<AppParkArea> parkAreaList = appPark.getParkAreaList();
        appParkAreaService.remove(Wrappers.<AppParkArea>lambdaQuery().eq(AppParkArea::getParkCode, appPark.getCode()));
        appParkAreaService.saveBatch(parkAreaList);
        String imagePath = null;
        if (appPark.getIsDel() == 1) {
            return appParkService.saveOrUpdate(appPark, Wrappers.<AppPark>lambdaUpdate().eq(AppPark::getCode, appPark.getCode()));
        }
        try {
            imagePath = FileUpload.uploadImage(appPark.getSignPhoto(), picturePath);
            appPark.setSignPhoto(imagePath);
            return appParkService.saveOrUpdate(appPark, Wrappers.<AppPark>lambdaUpdate().eq(AppPark::getCode, appPark.getCode()));
        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        }

    }

}
